<?php

class UserObserver implements SplSubject
{
    public $loginNum;
    public $hobby;

    protected $observers = null;

    public function __construct($hobby)
    {
        $this->loginNum = rand(1, 10);
        $this->hobby = $hobby;
        $this->observers = new SplObjectStorage();
    }

    public function login(){
        // todo
        $this->notify();
    }

    /**
     * 观察
     * @param SplObserver $observer
     * @return void
     */
    public function attach(SplObserver $observer): void
    {
        // TODO: Implement attach() method.
        $this->observers->attach($observer);
    }

    /**
     * 移除
     * @param SplObserver $observer
     * @return void
     */
    public function detach(SplObserver $observer): void
    {
        // TODO: Implement detach() method.
        $this->observers->detach($observer);
    }

    /**
     * 通知
     * @return void
     */
    public function notify(): void
    {
        // TODO: Implement notify() method.
        $this->observers->rewind();
        while ($this->observers->valid()) {
            $observer = $this->observers->current();
            $observer->update($this);
            $this->observers->next();
        }
    }
}

class secrity implements SplObserver
{
    public function update(SplSubject $subject): void
    {
        if ($subject->loginNum < 3) {
            echo "这是第 " . $subject->loginNum . " 次安全登录" .PHP_EOL;
        } else {
            echo "这是第 " . $subject->loginNum . " 次登录，异常登录" .PHP_EOL;
        }
    }
}

class ad implements SplObserver
{
    public function update(SplSubject $subject): void
    {
        if ($subject->hobby == "sports") {
            echo "篮球、足球、羽毛球" .PHP_EOL;
        } else {
            echo "干点其他的事情吧" .PHP_EOL;
        }
    }
}

$user = new UserObserver('sports');
$user->attach(new secrity());
$user->attach(new ad());

$user->login();
